var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var queryurl = config.BASEPATH+'stock/price/temp_list';

var _height = $(parent).height()-220,_width = $(parent).width()-2;

var Choose = {
	importDraft:function(){
		commonDia = $.dialog({
			title : '选择草稿',
			content : 'url:'+config.BASEPATH+'stock/price/to_list_draft_dialog',
			data : {},
			width : 720,
			height : 420,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				Choose.doImportDraft(selected);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					Choose.doImportDraft(selected);
				}
			},
			cancel:true
		});
	},
	doImportDraft:function(rowData){
		$("#pc_date").val(rowData.pc_date);
		$("#pc_manager").val(rowData.pc_manager);
		$("#pc_remark").val(rowData.pc_remark);
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'stock/price/temp_import_draft',
			data:{pc_number:rowData.pc_number},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : "导入成功！"});
					THISPAGE.reloadGridData();
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	selectProduct:function(){
		commonDia = $.dialog({
			title : '选择商品',
			content : 'url:'+config.BASEPATH+'base/product/to_list_dialog',
			data : {multiselect:true,searchContent:$.trim($("#pd_no").val())},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				return Choose.temp_save(selected);
			},
			cancel:true
		});
	},
	temp_save:function(rowDatas){
		var products = [];
		for (var i = 0; i < rowDatas.length; i++) {
			var product = {};
			product.pcl_pd_code = rowDatas[i].pd_code;
			product.pcl_oldprice = rowDatas[i].pd_cost_price;
			product.pcl_newprice = rowDatas[i].pd_cost_price;
			products.push(product);
		}
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'stock/price/temp_save',
			data:{"products":JSON.stringify(products)},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '保存成功!'});
					THISPAGE.reloadGridData();
					commonDia.close();
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
		return false;
	}
};

var Utils = {
	doQueryEmp : function(){
		commonDia = $.dialog({
			title : '选择经办人',
			content : 'url:'+config.BASEPATH+'base/emp/to_list_dialog',
			data : {multiselect:false},
			width : 450,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				$("#pc_manager").val(selected.em_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					$("#pc_manager").val(selected.em_name);
				}
			},
			cancel:true
		});
	}
};

var handle = {
	temp_update:function(rowid,price){
		$.ajax({
			type:"POST",
			url:config.BASEPATH+'stock/price/temp_update',
			data:{pcl_id:rowid,pcl_newprice:price},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
				}else{
					Public.tips({type: 1, content : data.message});
				}
			}
		});
    },
	temp_del: function(rowId){//删除
		if(rowId != null && rowId != ''){
			var rowData = $("#grid").jqGrid("getRowData", rowId);
		 	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
				$.ajax({
					type:"POST",
					url:config.BASEPATH+'stock/price/temp_del',
					data:{"pcl_id":rowId},
					cache:false,
					dataType:"json",
					success:function(data){
						if(undefined != data && data.stat == 200){
							Public.tips({type: 3, content : '删除成功!'});
							$('#grid').jqGrid('delRowData', rowId);
						}else{
							Public.tips({type: 1, content : data.message});
						}
					}
				});
			});
	   }else{
		   Public.tips({type: 1, content : '请选择数据!'});
	   }	
    },
    temp_clear:function(){
    	$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
			$.ajax({
				type:"POST",
				url:config.BASEPATH+'stock/price/temp_clear',
				data:{},
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						Public.tips({type: 3, content : '删除成功!'});
						$("#grid").clearGridData();
					}else{
						Public.tips({type: 1, content : data.message});
					}
				}
			});
		});
    },
	save:function(isdraft){
		var pc_manager = $.trim($("#pc_manager").val());
		if(pc_manager == ""){
			Public.tips({type: 2, content : '请选择经办人！'});
			return;
		}
		var ids = $("#grid").jqGrid('getDataIDs');
		if (ids.length == 0){
			Public.tips({type: 2, content : '单据明细不存在，请选择货号！'});
			return;
		}
		$("#pc_isdraft").val(isdraft);
		$("#btn-save").attr("disabled",true);
		$("#btn-save-draft").attr("disabled",true);
		var saveUrl = config.BASEPATH+"stock/price/save";
		if($("#pc_id").val() != undefined){
			saveUrl = config.BASEPATH+"stock/price/update";
		}
		$.ajax({
			type:"POST",
			url:saveUrl,
			data:$('#form1').serialize(),
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '保存成功'});
					handle.loadData(data.data);
					setTimeout("api.zindex()",500);
				}else{
					Public.tips({type: 1, content : data.message});
					setTimeout("api.zindex()",500);
				}
				$("#btn-save").attr("disabled",false);
				$("#btn-save-draft").attr("disabled",false);
			}
		});
	},
	loadData:function(data){
		var pdata = {};
		pdata.id=data.pc_id;
		if(callback && typeof callback == 'function'){
			callback(pdata,oper,window);
		}
	},
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-image" title="图片">&#xe654;</i>';
		html_con += '</div>';
		return html_con;
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();
	},
	initDom:function(){
		$("#pc_date").val(config.TODAY);
        this.selectRow={};
	},
	initGrid:function(){
		var self=this;
		var colModel = [
		    {label:'操作',name:'operate', width: 70, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
		    {label:'',name: 'pcl_pd_code', index: 'pcl_pd_code', hidden:true},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60},
	    	{label:'调整前价格',name: 'pcl_oldprice', index: 'pcl_oldprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'调整后价格',name: 'pcl_newprice', index: 'pcl_newprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost,editable:PriceLimit.hasCost()}
	    ];
		$('#grid').jqGrid({
			url:queryurl,
			loadonce:true,
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:false,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
			cellEdit: true,
            cellsubmit: 'clientArray',
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'pcl_id'  //图标ID
			},
			loadComplete: function(data){
				var ids = $("#grid").getDataIDs();
			},
			loadError: function(xhr, status, error){		
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){
            	self.selectRow.value=value;
				return value;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				if (cellname == 'pcl_newprice' && self.selectRow.value != value){
					if(value == '' || isNaN(value) || parseFloat(value) < 0){
						return self.selectRow.value;
					}
					if(parseFloat(self.selectRow.value) == parseFloat(value)){
						return self.selectRow.value;
					}
					if(parseFloat(value).toFixed(2).length > 11 || parseFloat(value) >1e+11){
						return self.selectRow.value;
					}
					handle.temp_update(rowid, parseFloat(value).toFixed(2));
					return parseFloat(value).toFixed(2);
				}
				return value;
			}
	    });
	},
	reloadGridData: function () {
        $("#grid").jqGrid('setGridParam', {datatype: 'json', page: 1, url: queryurl}).trigger("reloadGrid");
    },
	initEvent:function(){
		$('#btn-save').on('click', function(e){
			e.preventDefault();
			handle.save(0);
		});
		$('#btn-save-draft').on('click', function(e){
			e.preventDefault();
			handle.save(1);
		});
		$('#btn-import-draft').on('click', function(e){
			e.preventDefault();
			Choose.importDraft();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
		//清除
        $('#btnClear').click(function(e){
        	e.preventDefault();
        	handle.temp_clear();
		});
        //删除-列表模式
		$('#grid').on('click', '.operating .ui-icon-trash', function(e) {
			e.preventDefault();
			var id = $(this).parent().data('id');
			handle.temp_del(id);
		});
		
		$('#grid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#grid").jqGrid("getRowData", id).pcl_pd_code);
        });
	}
};

THISPAGE.init();